﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFromTools
{
    public partial class CopyFileForm : Form
    {
        public CopyFileForm()
        {
            InitializeComponent();
        }

        private void btnSelectOriginal_Click(object sender, EventArgs e)
        {
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                txtOriginalPath.Text = folderDialog.SelectedPath;
            }
        }

        private void btnSelectDesc_Click(object sender, EventArgs e)
        {
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                txtDescPath.Text = folderDialog.SelectedPath;
            }
        }

        private void btnCopyFile_Click(object sender, EventArgs e)
        {
            CopyDir(txtOriginalPath.Text, txtDescPath.Text, txtDescExt.Text, txtFileNames, !chkDontCopy.Checked);

            WriteLine(txtFileNames, "复制完成");
        }

        #region Helper

        private static void WriteLine(TextBox txtBox, String text)
        {
            txtBox.Focus();
            txtBox.AppendText(text + Environment.NewLine);
            txtBox.ScrollToCaret();
            System.Windows.Forms.Application.DoEvents();
        }

        public static void CopyDir(string srcPath, string destPath, string include, TextBox txtBox, bool copy = true)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (destPath[destPath.Length - 1] != Path.DirectorySeparatorChar)
                {
                    destPath += Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(destPath) && copy)
                    Directory.CreateDirectory(destPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        string pathName = Path.GetFileName(file).ToLower();
                        //if (pathName.ToLower() == "bin" || pathName.ToLower() == "obj" || pathName.ToLower() == "" || pathName.ToLower() == "")
                        if (ContainString(pathName.ToLower(), ".vs", "$tf", "bin", "obj", ".svn", "_svn", "packages", "node_modules", ".nuget", ".git", ".vscode"))
                        {
                            continue;//  ".nuget", 
                        }

                        CopyDir(file, destPath + Path.GetFileName(file), include, txtBox, copy);
                    }
                    // 否则直接Copy文件
                    else
                    {
                        //string fileExtension = file.Substring(file.IndexOf(".") + 1);
                        string fileExtension = GetFileExtension(file);
                        if (!String.IsNullOrEmpty(fileExtension))
                        {
                            //if (fileExtension.ToLower() == ".dll" || fileExtension.ToLower() == ".scc" || fileExtension.ToLower() == ".vspscc" || fileExtension.ToLower() == ".suo")
                            if (ContainString(fileExtension.ToLower(), "$tf", ".scc", ".vspscc", ".suo", ".zip", ".vspscc", ".rar", ".exe", ".doc"))
                            {
                                continue;// ".nuget",  ".dll", 
                            }

                            if (!String.IsNullOrEmpty(include) && !ContainString(fileExtension.ToLower(), include.Split(';', ' ', ',')))
                            {
                                continue;
                            }
                        }
                        if(copy)
                            File.Copy(file, destPath + Path.GetFileName(file), true);
                        if (txtBox != null)
                        {
                            //if (file.Contains(@"\2.1.1\lib\netstandard2.0\"))
                            //{
                            //    WriteLine(txtBox, $"<Assembly>{file}</Assembly>");
                            //}
                            //WriteLine(txtBox, $"<File><FilePath>{file}</FilePath></File>");
                            WriteLine(txtBox, file);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        public static bool ContainString(string s, params string[] stringSet)
        {
            bool ret = false;
            foreach (string element in stringSet)
            {
                if (element.Trim().ToLower() == s.ToLower())
                {
                    ret = true;
                    break;
                }
            }

            return ret;
        }

        public static string GetFileExtension(string fileName)
        {
            int length = fileName.Length;
            int startIndex = length;
            while (--startIndex >= 0)
            {
                char ch = fileName[startIndex];
                if (ch == '.')
                {
                    return fileName.Substring(startIndex, length - startIndex);
                }
                if (((ch == Path.DirectorySeparatorChar) || (ch == Path.AltDirectorySeparatorChar)) || (ch == Path.VolumeSeparatorChar))
                {
                    break;
                }
            }
            return string.Empty;
        }

        #endregion

        public static void HandleFile(List<String> ext, string srcPath, TextBox txtBox)
        {
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                {
                    string pathName = Path.GetFileName(file).ToLower();
                    //if (pathName.ToLower() == "bin" || pathName.ToLower() == "obj" || pathName.ToLower() == "" || pathName.ToLower() == "")
                    if (ContainString(pathName.ToLower(), ".vs", "$tf", "bin", "obj", ".svn", "_svn", "packages", "node_modules", ".nuget", ".git", ".vscode"))
                    {
                        continue;//  ".nuget", 
                    }

                    HandleFile(ext, file, txtBox);
                }
                else
                {
                    //string fileExtension = file.Substring(file.IndexOf(".") + 1);
                    string fileExtension = GetFileExtension(file);
                    if (!String.IsNullOrEmpty(fileExtension))
                    {
                        if (!ext.Contains(fileExtension))
                        {
                            ext.Add(fileExtension);

                            if (txtBox != null)
                            {
                                WriteLine(txtBox, fileExtension);
                            }
                        }
                    }

                    if (txtBox != null)
                    {
                        WriteLine(txtBox, file);
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var srcPath = txtOriginalPath.Text;

            List<String> ext = new List<String>();

            HandleFile(ext, srcPath, txtFileNames);
            ext.Sort();
            WriteLine(txtFileNames, String.Join(", ", ext));
        }

        private void btnFindFiles_Click(object sender, EventArgs e)
        {
            var srcPath = txtOriginalPath.Text;
            ListFile( srcPath, txtFileNames);
        }

        public static void ListFile(string srcPath, TextBox txtBox)
        {
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                {
                    string pathName = Path.GetFileName(file).ToLower();
                    //if (pathName.ToLower() == "bin" || pathName.ToLower() == "obj" || pathName.ToLower() == "" || pathName.ToLower() == "")
                    if (ContainString(pathName.ToLower(), ".vs", "$tf", "bin", "obj", ".svn", "_svn", "packages", "node_modules", ".nuget", ".nupkg", ".git", ".vscode"))
                    {
                        continue;//  ".nuget", 
                    }

                    ListFile(file, txtBox);
                }
                else
                {
                    if (file.Contains(@"\2.2.0\lib\netstandard2.0\") && !file.EndsWith(".xml"))
                    {
                        WriteLine(txtBox, $"<Assembly>{file}</Assembly>");
                    }
                    ////WriteLine(txtBox, $"<File><FilePath>{file}</FilePath></File>");

                    //if (txtBox != null)
                    //{
                    //    WriteLine(txtBox, file);
                    //}
                }
            }
        }
    }
}
